package com.example.liuweather.android.Fragment;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.liuweather.android.MainActivity;
import com.example.liuweather.android.R;
import com.example.liuweather.android.RecyAdapter;
import com.example.liuweather.android.WeatherActivity;
import com.example.liuweather.android.db.City;
import com.example.liuweather.android.db.County;
import com.example.liuweather.android.db.Province;
import com.example.liuweather.android.util.HttpUtil;
import com.example.liuweather.android.util.LogUtil;
import com.example.liuweather.android.util.Utility;
import com.qweather.sdk.bean.base.Code;
import com.qweather.sdk.bean.base.Lang;
import com.qweather.sdk.bean.base.Range;
import com.qweather.sdk.bean.geo.GeoBean;
import com.qweather.sdk.view.QWeather;

import org.litepal.LitePal;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class ChooseAreaFragment extends Fragment {
    public static final int LEVEL_PROVINCE = 0;
    public static final int LEVEL_CITY = 1;
    public static final int LEVEL_COUNTY = 2;
    private ProgressDialog progressDialog;
    private TextView titleText;
    private ListView listView;
    private LinearLayout hotCityLayout;
    // 搜索
    private Button searchBn;
    private ImageView deleteBn;
    private EditText searchEditText;
    private ListView searchLv;
    private ArrayAdapter<String> adapter;
    private ArrayAdapter<String> resultAdapter;

    private List<String> dataList = new ArrayList<>();
    private List<String> resultList = new ArrayList<>();


    // 当前搜索结果
    List<GeoBean.LocationBean> resultLocationBeans = new ArrayList<>();
    // 热门城市
    private RecyclerView recyclerView;
    private List<GeoBean.LocationBean> hotCityLocationBean = new ArrayList<>();
    private List<String> hotCityNameList = new ArrayList<>();
    private List<String> hotCityIdList = new ArrayList<>();
    private RecyAdapter hotCityAdapter;
    /**
     * 省列表
     */
    private List<Province> provinceList;
    /**
     * 市列表
     */
    private List<City> cityList;
    /**
     * 县列表
     */
    private List<County> countyList;
    /**
     * 选中的省份
     */
    private Province selectedProvince;
    /**
     * 选中的城市
     */
    private City selectedCity;
    /**
     * 当前选中的级别
     */
    private int currentLevel;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.choose_area, container, false);
        titleText = (TextView) view.findViewById(R.id.title_text);
        // backButton = (Button) view.findViewById(R.id.back_button);
        searchBn = view.findViewById(R.id.search_bn);
        deleteBn = view.findViewById(R.id.delete_bn);
        searchLv = view.findViewById(R.id.search_result_list);
        searchEditText = view.findViewById(R.id.search_text);
        hotCityLayout = view.findViewById(R.id.hot_city_layout);
        // listView = (ListView) view.findViewById(R.id.list_view);
        // adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, dataList);
        // listView.setAdapter(adapter);
        resultAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, resultList);
        searchLv.setAdapter(resultAdapter);
        // 热门城市
        recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
        GridLayoutManager layoutManager = new GridLayoutManager(getContext(),6,LinearLayoutManager.VERTICAL,false);
        recyclerView.setLayoutManager(layoutManager);
        hotCityAdapter = new RecyAdapter(getContext(),hotCityNameList,hotCityIdList);
        recyclerView.setAdapter(hotCityAdapter);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // 加载热门城市数据
        queryHotCity();
        /**
         * 城市列表的子项点击事件
         * */
        // listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        //     @Override
        //     public void onItemClick(AdapterView<?> parent, View view, int position,
        //                             long id) {
        //         if (currentLevel == LEVEL_PROVINCE) {
        //             selectedProvince = provinceList.get(position);
        //             queryCities();
        //         } else if (currentLevel == LEVEL_CITY) {
        //             selectedCity = cityList.get(position);
        //             queryCounties();
        //         }else if (currentLevel == LEVEL_COUNTY) {
        //             String weatherId = countyList.get(position).getWeatherId();
        //             String countyName = countyList.get(position).getCountyName();
        //             renewWeather(weatherId,countyName);
        //         }
        //     }
        // });
        // 加载省级数据
        // queryProvinces();
        /**
         * 搜索结果列表的子项点击事件
         * */
        searchLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String weatherId = resultLocationBeans.get(position).getId();
                String countyName = resultLocationBeans.get(position).getName();
                // 请求更新天气数据
                renewWeather(weatherId,countyName);
            }
        });
        /**
         * 搜索功能
          */
        // 监听搜索框文本的变化，并动态显示城市列表
        searchEditText.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String loc = s.toString().trim();
                if(loc.length() > 0 ){
                    LogUtil.w("change" + loc);
                    deleteBn.setVisibility(View.VISIBLE);
                    // 获取城市列表
                    doSearchArea(loc);
                }else {
                    // 内容为空
                    deleteBn.setVisibility(View.GONE);
                    LogUtil.w("显示原先城市列表");
                    // listView.setVisibility(View.VISIBLE);
                    hotCityLayout.setVisibility(View.VISIBLE);
                    searchLv.setVisibility(View.GONE);
                }
            }
            @Override
            public void afterTextChanged(Editable s) {
                LogUtil.w("输入的城市为" + s.toString());
            }
        });

        /**
         * 绑定搜索按键，进行搜索地区并切换当前天气信息
         * 一个是回车按键进行搜索
         * 一个是搜索按钮 功能代码一样
         * */
        searchEditText.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if(keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
                    // Toast.makeText(getActivity(), "按下回车", Toast.LENGTH_SHORT).show();
                    // 触发搜索按钮点击事件
                    searchBn.performClick();
                    return true;
                }
                return false;
            }
        });
        searchBn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 获取数据
                String loc = searchEditText.getText().toString().trim();
                // 搜索地区
                if(!loc.isEmpty()) {
                    // 因为编辑框有文本变化实时监听，所以数据一般先获取到了
                    if(resultLocationBeans.size() > 0){
                        LogUtil.w("长度"+resultLocationBeans.size());
                        String weatherId = resultLocationBeans.get(0).getId();
                        String countyName = resultLocationBeans.get(0).getName();
                        renewWeather(weatherId,countyName);
                    }else Toast.makeText(getActivity(),"没有匹配的结果",Toast.LENGTH_SHORT).show();
                    // 失去焦点
                    searchEditText.clearFocus();
                }
                // 隐藏软键盘
                hideSoftInput(v);
            }
        });

        // 搜索框失去焦点的监听器
        searchEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                LogUtil.w("焦点是否在编辑框" + hasFocus);
                // 隐藏软键盘
                hideSoftInput(v);
            }
        });

        /**搜索框的删除按钮绑定点击事件*/
        deleteBn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 清除输入框的内容
                clearSearchEditText();
                // 隐藏删除按钮
                deleteBn.setVisibility(View.GONE);
            }
        });
    }

    /**
     * 当前碎片处于WeatherActivity或MainActvity中的刷新数据及页面
     * */
    public void renewWeather(String weatherId,String countyName){
        /*instanceof 关键字可以用来判断一个对象是否属于某个类的实例。*/
        if(getActivity() instanceof MainActivity){
            // 当前碎片处于MainActivity实例活动
            Intent intent = new Intent(getActivity(), WeatherActivity.
                    class);
            intent.putExtra("weather_id", weatherId);
            intent.putExtra("county_name", countyName);
            startActivity(intent);
            getActivity().finish();
        }else if(getActivity() instanceof WeatherActivity){
            // 当前碎片处于 WeatherActivity 实例活动
            WeatherActivity activity = (WeatherActivity) getActivity();
            // 关闭滑动菜单
            activity.drawerLayout.closeDrawers();
            // 显示下拉刷新进度条
            activity.swipeRefresh.setRefreshing(true);
            activity.weatherId = weatherId;
            activity.countyName = countyName;
            // 重新请求数据
            activity.requestWeatherForQWeather(weatherId);
        }

    }
    /**
     * 清空搜索框
    * */
    public boolean clearSearchEditText(){
        searchEditText.setText("");
        return true;
    }

    /**
     * 隐藏软键盘
     * */
    private void hideSoftInput(View v){
        InputMethodManager inputMethodManager = (InputMethodManager) getContext().getSystemService(Activity.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        return ;
    }

    /**
     * 搜索功能：获取城市地区数据及显示列表，支持模糊搜索
     * */
    private void doSearchArea(String loc){
        // 清除原有适配器绑定的数据
        resultList.clear();
        // 将原有数据清空
        resultLocationBeans.clear();
        QWeather.getGeoCityLookup(getContext(), loc, Range.CN, 10, Lang.ZH_HANS, new QWeather.OnResultGeoListener() {
            @Override
            public void onError(Throwable throwable) {
                String text = searchEditText.getText().toString().trim();
                // 解决长按删除输入框清空，刷新视图异步比同步慢的问题，重新还原城市列表
                if(text.isEmpty()){
                    // listView.setVisibility(View.VISIBLE);
                    hotCityLayout.setVisibility(View.VISIBLE);
                    searchLv.setVisibility(View.GONE);
                }else showCountyListView();
                LogUtil.w("ChooseAreaFragment doSearchArea onError : " + throwable);
            }

            @Override
            public void onSuccess(GeoBean geoBean) {
                if(geoBean.getCode() == Code.OK){
                    resultLocationBeans = geoBean.getLocationBean();
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            for(GeoBean.LocationBean loc : resultLocationBeans){
                                String locName =  loc.getName(); // 地区 or 城市名称
                                String locAdm2 = loc. getAdm2(); // 该地区／城市的上级城市
                                String locAdm1 = loc.getAdm1(); // 该地区／城市所属行政区域
                                String locCountry = loc.getCountry(); // 该地区／城市所属国家名称
                                resultList.add(locName + "," + locAdm2 + "," + locAdm1 + "," + locCountry);
                            }
                            // 获取当前输入框的字符串
                            String text = searchEditText.getText().toString().trim();
                            // 解决长按删除输入框清空，刷新视图异步比同步慢的问题，重新还原城市列表
                            if(text.isEmpty()){
                                // listView.setVisibility(View.VISIBLE);
                                hotCityLayout.setVisibility(View.VISIBLE);
                                searchLv.setVisibility(View.GONE);
                            }else
                                showCountyListView();
                            LogUtil.w("搜索地区列表成功");
                        }
                    });
                }else {
                    // 刷新适配器
                    showCountyListView();
                    // 在此查看返回数据失败的原因
                    Code code = geoBean.getCode();
                    LogUtil.w("doSearchArea failed code: " + code);
                }
            }
        });

    }
    /**
     * 刷新适配器，切换到搜索结果列表视图
     * */
    private void showCountyListView(){
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // 刷新适配器
                resultAdapter.notifyDataSetChanged();
                // 显示视图
                searchLv.setSelection(0);
                searchLv.setVisibility(View.VISIBLE);
                // listView.setVisibility(View.GONE);
                hotCityLayout.setVisibility(View.GONE);
            }
        });
        return;
    }
    /**
     * 返回热门城市数据并刷新页面
     * */
    private void queryHotCity(){
        // 清除原有数据
        hotCityIdList.clear();
        hotCityNameList.clear();
        // 请求数据
        QWeather.getGeoTopCity(getContext(), 12, Range.CN, Lang.ZH_HANS, new QWeather.OnResultGeoListener() {
            @Override
            public void onError(Throwable throwable) {

            }

            @Override
            public void onSuccess(GeoBean geoBean) {
                if(geoBean.getCode() == Code.OK){
                    hotCityLocationBean = geoBean.getLocationBean();
                    // 保存数据
                    for(GeoBean.LocationBean loc : hotCityLocationBean){
                        String name = loc.getName();
                        String id = loc.getId();
                        hotCityIdList.add(id);
                        hotCityNameList.add(name + "市");
                    }
                    // 更新页面
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            // 刷新适配器
                            hotCityAdapter.notifyDataSetChanged();
                        }
                    });
                }else {
                    // 在此查看返回数据失败的原因
                    Code code = geoBean.getCode();
                    LogUtil.w("queryHotCity failed code: " + code);
                }
            }
        });
    }



    /**
     * 查询全国所有的省，优先从数据库查询，如果没有查询到再去服务器上查询
     */
    // private void queryProvinces() {
    //     titleText.setText("中国");
    //     // 隐藏返回按钮
    //     backButton.setVisibility(View.GONE);
    //     provinceList = LitePal.findAll(Province.class);
    //     if (provinceList.size() > 0) {
    //         // 将原有数据清除
    //         dataList.clear();
    //         // 更新数据
    //         for (Province province : provinceList) {
    //             dataList.add(province.getProvinceName());
    //         }
    //         // 适配器刷新
    //         adapter.notifyDataSetChanged();
    //         listView.setSelection(0);
    //         currentLevel = LEVEL_PROVINCE;
    //     } else {
    //         String address = "http://guolin.tech/api/china";
    //         queryFromServer(address, "province");
    //     }
    // }
    /**
     * 查询选中省内所有的市，优先从数据库查询，如果没有查询到再去服务器上查询
     */
    // private void queryCities() {
    //     titleText.setText(selectedProvince.getProvinceName());
    //     backButton.setVisibility(View.VISIBLE);
    //     // 直接在数据库中查询
    //     cityList = LitePal.where("provinceid = ?", String.valueOf(selectedProvince.getId())).find(City.class);
    //     if (cityList.size() > 0) {
    //         // 数据库中已存在
    //         dataList.clear();
    //         for (City city : cityList) {
    //             dataList.add(city.getCityName());
    //         }
    //         adapter.notifyDataSetChanged();
    //         listView.setSelection(0);
    //         currentLevel = LEVEL_CITY;
    //     } else {
    //         // 数据库中没有，则请求访问服务器访问数据并将数据保存在数据库中
    //         int provinceCode = selectedProvince.getProvinceCode();
    //         String address = "http://guolin.tech/api/china/" + provinceCode;
    //         queryFromServer(address, "city");
    //     }
    // }
    /**
     * 查询选中市内所有的县，优先从数据库查询，如果没有查询到再去服务器上查询
     */
    // private void queryCounties() {
    //     titleText.setText(selectedCity.getCityName());
    //     backButton.setVisibility(View.VISIBLE);
    //     countyList = LitePal.where("cityid = ?", String.valueOf(selectedCity.getId())).find(County.class);
    //     if (countyList.size() > 0) {
    //         dataList.clear();
    //         for (County county : countyList) {
    //             dataList.add(county.getCountyName());
    //         }
    //         adapter.notifyDataSetChanged();
    //         listView.setSelection(0);
    //         currentLevel = LEVEL_COUNTY;
    //     } else {
    //         int provinceCode = selectedProvince.getProvinceCode();
    //         int cityCode = selectedCity.getCityCode();
    //         String address = "http://guolin.tech/api/china/" + provinceCode + "/" +
    //                 cityCode;
    //         queryFromServer(address, "county");
    //     }
    // }
    /**
     * 根据传入的地址和类型从服务器上查询省市县数据
     */
    // private void queryFromServer(String address, final String type) {
    //     showProgressDialog();
    //     HttpUtil.sendOkHttpRequest(address, new Callback() {
    //         /*
    //         最终的回调接口都还是在子线程中运行的，所以进行任何UI操作需要切换到主线程
    //         */
    //         @Override
    //         public void onResponse(Call call, Response response) throws IOException {
    //             // 获取服务器数据
    //             String responseText = response.body().string();
    //             boolean result = false;
    //             if ("province".equals(type)) {
    //                 result = Utility.handleProvinceResponse(responseText);
    //             } else if ("city".equals(type)) {
    //                 result = Utility.handleCityResponse(responseText,
    //                         selectedProvince.getId());
    //             } else if ("county".equals(type)) {
    //                 result = Utility.handleCountyResponse(responseText,
    //                         selectedCity.getId());
    //             }
    //             if (result) {
    //                 getActivity().runOnUiThread(new Runnable() {
    //                     @Override
    //                     public void run() {
    //                         closeProgressDialog();
    //                         if ("province".equals(type)) {
    //                             queryProvinces();
    //                         } else if ("city".equals(type)) {
    //                             queryCities();
    //                         } else if ("county".equals(type)) {
    //                             queryCounties();
    //                         }
    //                     }
    //                 });
    //             }
    //         }
    //         @Override
    //         public void onFailure(Call call, IOException e) {
    //             // 通过runOnUiThread()方法回到主线程处理逻辑
    //             getActivity().runOnUiThread(new Runnable() {
    //                 @Override
    //                 public void run() {
    //                     closeProgressDialog();
    //                     Toast.makeText(getContext(), "加载失败", Toast.LENGTH_SHORT).
    //                             show();
    //                 }
    //             });
    //         }
    //     });
    // }
    /**
     * 显示进度对话框
     */
    private void showProgressDialog() {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(getActivity());
            progressDialog.setMessage("正在加载...");
            //触摸屏幕外不消失
            progressDialog.setCanceledOnTouchOutside(false);
        }
        progressDialog.show();
    }
    /**
     * 关闭进度对话框
     */
    private void closeProgressDialog() {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }
}
